package com.htgd.gardenexpo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dao.*;
import com.htgd.gardenexpo.entity.CommonResult;
import com.htgd.gardenexpo.entity.GeConSportsMax;
import com.htgd.gardenexpo.service.IGeConWeatherService;
import com.htgd.gardenexpo.service.ISportsService;
import com.htgd.gardenexpo.utils.WeatherUtils;
import com.htgd.gardenexpo.vo.CurrentTaskVO;
import com.htgd.gardenexpo.vo.MySportsRecordVO;
import com.htgd.gardenexpo.vo.MySportsVO;
import com.htgd.gardenexpo.vo.SportsDataVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.htgd.gardenexpo.utils.CalculationUtils.*;
import static com.htgd.gardenexpo.utils.CommonUtils.kCalorie;
import static com.htgd.gardenexpo.utils.CommonUtils.mergeList;
import static com.htgd.gardenexpo.utils.DateUtils.getDayOfWeek;
import static com.htgd.gardenexpo.utils.DateUtils.getWeekDate;
import static com.htgd.gardenexpo.utils.TimeUtils.convertSecondsToMinutes;
import static com.htgd.gardenexpo.utils.TimeUtils.formatSecondsToTime;

/**
 * @author lihailong
 * @date
 */
@Service
public class SportsServiceImpl implements ISportsService {

    @Autowired
    private WxUserDao wxUserDao;

    @Autowired
    private GeConDailyDataDeckMapper geConDailyDataDeckMapper;

    @Autowired
    private GeConLeisureDataDeckMapper geConLeisureDataDeckMapper;

    @Autowired
    private GeConFreeSportsMapper geConFreeSportsMapper;

    @Autowired
    private GeConGoalSportsMapper geConGoalSportsMapper;

    @Autowired
    private GeConChallengeSportsMapper geConChallengeSportsMapper;

    @Autowired
    private GeConSportsMaxMapper geConSportsMaxMapper;

    @Autowired
    private SportsMapper sportsMapper;

    @Autowired
    private IGeConWeatherService geConWeatherService;

    @Autowired
    private WeatherUtils weatherUtils;

    @Autowired
    private GeConLeisureSportsMapper geConLeisureSportsMapper;

    @Autowired
    private GeConChallengeSportsTaskMapper geConChallengeSportsTaskMapper;

    @Override
    public CommonResult getMySportsData(String openId) {
        SportsDataVO sportsDataVO = new SportsDataVO();

        //获取甲板id
        String deckId = wxUserDao.getDeckId(openId);

        //总里程
        double dailySumMileage = 0;
        double leisureSumMileage = 0;
        if(deckId!=null){
            //甲板日常数据
            dailySumMileage = geConDailyDataDeckMapper.getSumMileageByDeckId(deckId);
            //甲板挑战数据
            leisureSumMileage = geConLeisureDataDeckMapper.getSumMileageByOpenId(deckId);
        }
        //自由跑数据
        double freeSumMileage = geConFreeSportsMapper.getSumMileageByOpenId(openId);
        //目标跑数据
        double goalSumMileage = geConGoalSportsMapper.getSumMileageByOpenId(openId);
        //挑战跑数据
        double challengeSumMileage = geConChallengeSportsMapper.getSumMileageByOpenId(openId);


        sportsDataVO.setTotalMileage(String.format("%.2f",dailySumMileage+leisureSumMileage+freeSumMileage+goalSumMileage+challengeSumMileage));

        //周数据
        double[] weekMileage = new double[7];  // 将 weekMileage 改为 double 数组
        List<String> weekDate = getWeekDate();

        if (deckId != null) {
            for (int i = 0; i < 7; i++) {
                // 日常
                double dailyMileage = geConDailyDataDeckMapper.getSumMileageByDeckIdAndDate(deckId, weekDate.get(i));
                weekMileage[i] += dailyMileage;

                // 挑战
                double leisureMileage = geConLeisureDataDeckMapper.getSumMileageByDeckIdAndDate(deckId, weekDate.get(i));
                weekMileage[i] += leisureMileage;
            }
        }

        for (int i = 0; i < 7; i++) {
            // 自由
            double freeMileage = geConFreeSportsMapper.getSumMileageByOpenIdAndDate(openId, weekDate.get(i));
            weekMileage[i] += freeMileage;

            // 目标
            double goalMileage = geConGoalSportsMapper.getSumMileageByOpenIdAndDate(openId, weekDate.get(i));
            weekMileage[i] += goalMileage;

            // 挑战
            double challengeMileage = geConChallengeSportsMapper.getSumMileageByOpenIdAndDate(openId, weekDate.get(i));
            weekMileage[i] += challengeMileage;
        }

// 将 double 数组转为 String 类型以便传递给 VO
        String[] weekMileageStr = new String[7];
        for (int i = 0; i < 7; i++) {
            weekMileageStr[i] = String.format("%.2f", weekMileage[i]);
        }

        sportsDataVO.setWeekMileage(weekMileageStr);  // 设置到 VO


        //今日
        int dayOfWeek = getDayOfWeek();
        sportsDataVO.setToday(dayOfWeek);

        //天气
        JSONObject weather = geConWeatherService.getWeather();
        if(weather!=null){
            JSONObject weatherNew = weatherUtils.addLogo(weather);
            sportsDataVO.setWeather(weatherNew);
        }
        return CommonResult.success("查询成功",sportsDataVO);
    }

    @Override
    public CommonResult getMySports(String openId) {
        MySportsVO mySportsVO = new MySportsVO();

        //获取甲板id
        String deckId = wxUserDao.getDeckId(openId);

        //总距离
        double dailySumMileage = 0;
        double leisureSumMileage = 0;
        if(deckId!=null){
            //甲板日常数据
            dailySumMileage = geConDailyDataDeckMapper.getSumMileageByDeckId(deckId);
            //甲板挑战数据
            leisureSumMileage = geConLeisureDataDeckMapper.getSumMileageByOpenId(deckId);
        }
        //自由跑数据
        double freeSumMileage = geConFreeSportsMapper.getSumMileageByOpenId(openId);
        //目标跑数据
        double goalSumMileage = geConGoalSportsMapper.getSumMileageByOpenId(openId);
        //挑战跑数据
        double challengeSumMileage = geConChallengeSportsMapper.getSumMileageByOpenId(openId);

        mySportsVO.setTotalMileage(String.format("%.2f",dailySumMileage+leisureSumMileage+freeSumMileage+goalSumMileage+challengeSumMileage));

        //总时长
        double dailySumDuration = 0;
        double leisureSumDuration = 0;
        if(deckId!=null){
            //甲板日常数据
            dailySumDuration = geConDailyDataDeckMapper.getSumDurationByDeckId(deckId);
            //甲板挑战数据
            leisureSumDuration = geConLeisureDataDeckMapper.getSumDurationByDeckId(deckId);
        }
        //自由跑数据
        double freeSumDuration = geConFreeSportsMapper.getSumDurationByOpenId(openId);
        //目标跑数据
        double goalSumDuration = geConGoalSportsMapper.getSumDurationByOpenId(openId);
        //挑战跑数据
        double challengeSumDuration = geConChallengeSportsMapper.getSumDurationByOpenId(openId);

        int minutes = convertSecondsToMinutes((long) (dailySumDuration + leisureSumDuration + freeSumDuration + goalSumDuration + challengeSumDuration));

        mySportsVO.setTotalDuration(String.valueOf(minutes));

        GeConSportsMax geConSportsMax = geConSportsMaxMapper.selectOne(new LambdaQueryWrapper<GeConSportsMax>().eq(GeConSportsMax::getOpenId, openId));
        if(geConSportsMax!=null){
            mySportsVO.setMaxCalorie(geConSportsMax.getMaxCalorie());
            String maxDuration = formatSecondsToTime(Long.parseLong(geConSportsMax.getMaxDuration()));
            mySportsVO.setMaxDuration(maxDuration);
            mySportsVO.setMaxMileage(geConSportsMax.getMaxMileage());
        }else {
            mySportsVO.setMaxCalorie("0");
            mySportsVO.setMaxDuration("00:00:00");
            mySportsVO.setMaxMileage("0");
        }

        return CommonResult.success("查询成功",mySportsVO);
    }

    @Override
    public CommonResult getSportsRecord(String openId, Integer pageNum, Integer pageSize, String type) {

        //获取甲板id
        String deckId = wxUserDao.getDeckId(openId);

        if("1".equals(type)){//自由跑
            PageHelper.startPage(pageNum,pageSize);
            List<MySportsRecordVO> mySportsRecordVOS = geConFreeSportsMapper.getSportsRecord(openId);
            for (MySportsRecordVO mySportsRecordVO : mySportsRecordVOS) {
                //用时
                String duration2 = formatSecondsToTime(mySportsRecordVO.getDuration());
                mySportsRecordVO.setDuration2(duration2);
                //速度
                String speed = getSpeed(mySportsRecordVO.getDuration(), Double.parseDouble(mySportsRecordVO.getMileage()));
                mySportsRecordVO.setSpeed(speed);
            }
            PageInfo<MySportsRecordVO> list = new PageInfo<>(mySportsRecordVOS);
            return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
        } else if ("2".equals(type)) {//目标跑
            PageHelper.startPage(pageNum,pageSize);
            List<MySportsRecordVO> mySportsRecordVOS = geConGoalSportsMapper.getSportsRecord(openId);
            for (MySportsRecordVO mySportsRecordVO : mySportsRecordVOS) {
                //用时
                String duration2 = formatSecondsToTime(mySportsRecordVO.getDuration());
                mySportsRecordVO.setDuration2(duration2);
                //速度
                String speed = getSpeed(mySportsRecordVO.getDuration(), Double.parseDouble(mySportsRecordVO.getMileage()));
                mySportsRecordVO.setSpeed(speed);
            }
            PageInfo<MySportsRecordVO> list = new PageInfo<>(mySportsRecordVOS);
            return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
        }  else if ("3".equals(type)) {//挑战跑
            PageHelper.startPage(pageNum,pageSize);
            List<MySportsRecordVO> mySportsRecordVOS = geConChallengeSportsMapper.getSportsRecord(openId);
            for (MySportsRecordVO mySportsRecordVO : mySportsRecordVOS) {
                //用时
                String duration2 = formatSecondsToTime(mySportsRecordVO.getDuration());
                mySportsRecordVO.setDuration2(duration2);
                //速度
                String speed = getSpeed(mySportsRecordVO.getDuration(), Double.parseDouble(mySportsRecordVO.getMileage()));
                mySportsRecordVO.setSpeed(speed);
            }
            PageInfo<MySportsRecordVO> list = new PageInfo<>(mySportsRecordVOS);
            return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
        }else if ("4".equals(type)) { //智慧起跑线
            if(deckId!=null){
                PageHelper.startPage(pageNum,pageSize);
                List<MySportsRecordVO> mySportsRecordVOS = geConDailyDataDeckMapper.getSportsRecord(deckId);
                for (MySportsRecordVO mySportsRecordVO : mySportsRecordVOS) {
                    //用时
                    String duration2 = formatSecondsToTime(mySportsRecordVO.getDuration());
                    mySportsRecordVO.setDuration2(duration2);
                    //速度
                    String speed = getSpeed(mySportsRecordVO.getDuration(), Double.parseDouble(mySportsRecordVO.getMileage()));
                    mySportsRecordVO.setSpeed(speed);
                }
                PageInfo<MySportsRecordVO> list = new PageInfo<>(mySportsRecordVOS);
                return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
            }else {
                return CommonResult.success("0",new ArrayList<>());
            }
        }else if("5".equals(type)){ //挑战
            if(deckId!=null){
                PageHelper.startPage(pageNum,pageSize);
                List<MySportsRecordVO> mySportsRecordVOS = geConLeisureDataDeckMapper.getSportsRecord(deckId);
                for (MySportsRecordVO mySportsRecordVO : mySportsRecordVOS) {
                    //用时
                    String duration2 = formatSecondsToTime(mySportsRecordVO.getDuration());
                    mySportsRecordVO.setDuration2(duration2);
                    //速度
                    String speed = getSpeed(mySportsRecordVO.getDuration(), Double.parseDouble(mySportsRecordVO.getMileage()));
                    mySportsRecordVO.setSpeed(speed);
                }
                PageInfo<MySportsRecordVO> list = new PageInfo<>(mySportsRecordVOS);
                return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
            }else {
                return CommonResult.success("0",new ArrayList<>());
            }
        }else { //全部
            if(deckId!=null){
                PageHelper.startPage(pageNum,pageSize);
                List<MySportsRecordVO> mySportsRecordVOS = sportsMapper.getSportsRecord(openId,deckId);
                for (MySportsRecordVO mySportsRecordVO : mySportsRecordVOS) {
                    //用时
                    String duration2 = formatSecondsToTime(mySportsRecordVO.getDuration());
                    mySportsRecordVO.setDuration2(duration2);
                    //速度
                    String speed = getSpeed(mySportsRecordVO.getDuration(), Double.parseDouble(mySportsRecordVO.getMileage()));
                    mySportsRecordVO.setSpeed(speed);
                }
                PageInfo<MySportsRecordVO> list = new PageInfo<>(mySportsRecordVOS);
                return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
            }else {
                PageHelper.startPage(pageNum,pageSize);
                List<MySportsRecordVO> mySportsRecordVOS = sportsMapper.getSportsRecord2(openId);
                for (MySportsRecordVO mySportsRecordVO : mySportsRecordVOS) {
                    //用时
                    String duration2 = formatSecondsToTime(mySportsRecordVO.getDuration());
                    mySportsRecordVO.setDuration2(duration2);
                    //速度
                    String speed = getSpeed(mySportsRecordVO.getDuration(), Double.parseDouble(mySportsRecordVO.getMileage()));
                    mySportsRecordVO.setSpeed(speed);
                }
                PageInfo<MySportsRecordVO> list = new PageInfo<>(mySportsRecordVOS);
                return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
            }
        }

    }

    @Override
    public CommonResult getCurrentTask(String openId) {
        CurrentTaskVO currentTaskVO = sportsMapper.getCurrentTask(openId);
        if(currentTaskVO!=null){
            if("1".equals(currentTaskVO.getType())){
                //轨迹
                List<String> tracks = geConFreeSportsMapper.getTaskTrack(currentTaskVO.getTaskId());
                String s = mergeList(tracks);
                currentTaskVO.setLine(s);
            }
            if("2".equals(currentTaskVO.getType())){
                //轨迹
                List<String> tracks = geConGoalSportsMapper.getTaskTrack(currentTaskVO.getTaskId());
                String s = mergeList(tracks);
                currentTaskVO.setLine(s);
            }

            if("3".equals(currentTaskVO.getType())){
                //轨迹
                List<String> tracks = geConChallengeSportsMapper.getTaskTrack(currentTaskVO.getTaskId());
                String s = mergeList(tracks);
                currentTaskVO.setLine(s);

                //挑战情况
                String deckId = wxUserDao.getDeckId(openId);
                Map<String,Object> completeDate2 = geConChallengeSportsTaskMapper.getCompleteData(openId, currentTaskVO.getLeisureId());
                if(deckId!=null){
                    Map<String,Object> completeDate = geConLeisureSportsMapper.getCompleteData(deckId,currentTaskVO.getLeisureId());
                    if("1".equals(currentTaskVO.getType1())){ //时长
                        //完成
                        BigDecimal duration = (BigDecimal) completeDate.get("duration");
                        BigDecimal duration2 = (BigDecimal) completeDate2.get("duration");
                        BigDecimal duration3 = duration.add(duration2);
                        currentTaskVO.setComplete(String.valueOf(duration3));
                    }else{
                        //完成
                        Double mileage = (Double) completeDate.get("mileage");
                        Double mileage2 = (Double) completeDate2.get("mileage");
                        Double mileage3 = mileage+ mileage2;
                        currentTaskVO.setComplete(String.valueOf(mileage3));
                    }
                }else {
                    if("1".equals(currentTaskVO.getType1())){ //时长
                        //完成
                        BigDecimal duration2 = (BigDecimal) completeDate2.get("duration");
                        currentTaskVO.setComplete(String.valueOf(duration2));
                    }else{
                        //完成
                        Double mileage2 = (Double) completeDate2.get("mileage");
                        currentTaskVO.setComplete(String.valueOf(mileage2));
                    }
                }
            }
        }

        return CommonResult.success("查询成功",currentTaskVO);
    }

    @Override
    public CommonResult getStatisticalAnalysis(String openId, String type1, String type2, String type3) {
//        //获取甲板id
//        String deckId = wxUserDao.getDeckId(openId);
//
//        if("1".equals(type1)){//自由跑
//            PageHelper.startPage(pageNum,pageSize);
//            List<MySportsRecordVO> mySportsRecordVOS = geConFreeSportsMapper.getSportsRecord(openId);
//            for (MySportsRecordVO mySportsRecordVO : mySportsRecordVOS) {
//                //用时
//                String duration2 = formatSecondsToTime(mySportsRecordVO.getDuration());
//                mySportsRecordVO.setDuration2(duration2);
//                //速度
//                String speed = getSpeed(mySportsRecordVO.getDuration(), Double.parseDouble(mySportsRecordVO.getMileage()));
//                mySportsRecordVO.setSpeed(speed);
//            }
//            PageInfo<MySportsRecordVO> list = new PageInfo<>(mySportsRecordVOS);
//            return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
//        } else if ("2".equals(type)) {//目标跑
//            PageHelper.startPage(pageNum,pageSize);
//            List<MySportsRecordVO> mySportsRecordVOS = geConGoalSportsMapper.getSportsRecord(openId);
//            for (MySportsRecordVO mySportsRecordVO : mySportsRecordVOS) {
//                //用时
//                String duration2 = formatSecondsToTime(mySportsRecordVO.getDuration());
//                mySportsRecordVO.setDuration2(duration2);
//                //速度
//                String speed = getSpeed(mySportsRecordVO.getDuration(), Double.parseDouble(mySportsRecordVO.getMileage()));
//                mySportsRecordVO.setSpeed(speed);
//            }
//            PageInfo<MySportsRecordVO> list = new PageInfo<>(mySportsRecordVOS);
//            return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
//        }  else if ("3".equals(type)) {//挑战跑
//            PageHelper.startPage(pageNum,pageSize);
//            List<MySportsRecordVO> mySportsRecordVOS = geConChallengeSportsMapper.getSportsRecord(openId);
//            for (MySportsRecordVO mySportsRecordVO : mySportsRecordVOS) {
//                //用时
//                String duration2 = formatSecondsToTime(mySportsRecordVO.getDuration());
//                mySportsRecordVO.setDuration2(duration2);
//                //速度
//                String speed = getSpeed(mySportsRecordVO.getDuration(), Double.parseDouble(mySportsRecordVO.getMileage()));
//                mySportsRecordVO.setSpeed(speed);
//            }
//            PageInfo<MySportsRecordVO> list = new PageInfo<>(mySportsRecordVOS);
//            return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
//        }else if ("4".equals(type)) { //智慧起跑线
//            if(deckId!=null){
//                PageHelper.startPage(pageNum,pageSize);
//                List<MySportsRecordVO> mySportsRecordVOS = geConDailyDataDeckMapper.getSportsRecord(deckId);
//                for (MySportsRecordVO mySportsRecordVO : mySportsRecordVOS) {
//                    //用时
//                    String duration2 = formatSecondsToTime(mySportsRecordVO.getDuration());
//                    mySportsRecordVO.setDuration2(duration2);
//                    //速度
//                    String speed = getSpeed(mySportsRecordVO.getDuration(), Double.parseDouble(mySportsRecordVO.getMileage()));
//                    mySportsRecordVO.setSpeed(speed);
//                }
//                PageInfo<MySportsRecordVO> list = new PageInfo<>(mySportsRecordVOS);
//                return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
//            }else {
//                return CommonResult.success("0",new ArrayList<>());
//            }
//        }else if("5".equals(type)){ //挑战
//            if(deckId!=null){
//                PageHelper.startPage(pageNum,pageSize);
//                List<MySportsRecordVO> mySportsRecordVOS = geConLeisureDataDeckMapper.getSportsRecord(deckId);
//                for (MySportsRecordVO mySportsRecordVO : mySportsRecordVOS) {
//                    //用时
//                    String duration2 = formatSecondsToTime(mySportsRecordVO.getDuration());
//                    mySportsRecordVO.setDuration2(duration2);
//                    //速度
//                    String speed = getSpeed(mySportsRecordVO.getDuration(), Double.parseDouble(mySportsRecordVO.getMileage()));
//                    mySportsRecordVO.setSpeed(speed);
//                }
//                PageInfo<MySportsRecordVO> list = new PageInfo<>(mySportsRecordVOS);
//                return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
//            }else {
//                return CommonResult.success("0",new ArrayList<>());
//            }
//        }else { //全部
//            if(deckId!=null){
//                PageHelper.startPage(pageNum,pageSize);
//                List<MySportsRecordVO> mySportsRecordVOS = sportsMapper.getSportsRecord(openId,deckId);
//                for (MySportsRecordVO mySportsRecordVO : mySportsRecordVOS) {
//                    //用时
//                    String duration2 = formatSecondsToTime(mySportsRecordVO.getDuration());
//                    mySportsRecordVO.setDuration2(duration2);
//                    //速度
//                    String speed = getSpeed(mySportsRecordVO.getDuration(), Double.parseDouble(mySportsRecordVO.getMileage()));
//                    mySportsRecordVO.setSpeed(speed);
//                }
//                PageInfo<MySportsRecordVO> list = new PageInfo<>(mySportsRecordVOS);
//                return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
//            }else {
//                PageHelper.startPage(pageNum,pageSize);
//                List<MySportsRecordVO> mySportsRecordVOS = sportsMapper.getSportsRecord2(openId);
//                for (MySportsRecordVO mySportsRecordVO : mySportsRecordVOS) {
//                    //用时
//                    String duration2 = formatSecondsToTime(mySportsRecordVO.getDuration());
//                    mySportsRecordVO.setDuration2(duration2);
//                    //速度
//                    String speed = getSpeed(mySportsRecordVO.getDuration(), Double.parseDouble(mySportsRecordVO.getMileage()));
//                    mySportsRecordVO.setSpeed(speed);
//                }
//                PageInfo<MySportsRecordVO> list = new PageInfo<>(mySportsRecordVOS);
//                return CommonResult.success(String.valueOf(list.getTotal()),list.getList());
//            }
//        }
        return null;
    }
}
